package com.zhh.srforum.provider;

import com.alibaba.fastjson.JSONObject;
import com.zhh.srforum.dto.AccessTokenDTO;
import com.zhh.srforum.dto.GiteeUser;
import okhttp3.*;
import org.springframework.stereotype.Component;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.IOException;



/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Zhao Haihang
 * @Date: 2020/11/03/17:38
 * @Description:
 */
@Component
public class GiteeProvider {

    /**
     * 获取token
     * @param accessTokenDTO
     * @return
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        String json = JSON.toJSONString(accessTokenDTO);
        RequestBody body = RequestBody.create(mediaType,json);
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String str = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(str);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过token 获取 gitee用户信息
     * @param accessToken
     * @return
     */
    public GiteeUser getGithubUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                .build();

        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            GiteeUser githubUser = JSON.parseObject(string, GiteeUser.class);
            return githubUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
